<template>
  <view class="my-posts">
 
    
    <!-- 帖子列表 -->
    <scroll-view 
      class="post-list" 
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="posts.length > 0">
        <view 
          class="post-item" 
          v-for="(post, index) in filteredPosts" 
          :key="post._id"
          @click="viewPostDetail(post)"
        >
          <view class="post-header">
            <view class="post-title">{{ post.title }}</view>
            <view class="post-status" :class="post.status">{{ getStatusText(post.status) }}</view>
          </view>
          <view class="post-content">{{ post.content }}</view>
          <view class="post-images" v-if="post.images && post.images.length > 0">
            <image 
              v-for="(img, imgIndex) in post.images.slice(0, 3)" 
              :key="imgIndex" 
              :src="img" 
              mode="aspectFill"
              @click.stop="previewImage(post.images, imgIndex)"
            ></image>
            <view class="image-count" v-if="post.images.length > 3">+{{ post.images.length - 3 }}</view>
          </view>
          <view class="post-footer">
            <view class="post-meta">
              <text class="post-time">{{ formatDate(post.createTime) }}</text>
              <text class="post-stats">
                <text class="iconfont icon-like"></text> {{ post.likeCount || 0 }}
                <text class="iconfont icon-comment"></text> {{ post.commentCount || 0 }}
              </text>
            </view>
            <view class="post-actions">
             <!-- <view class="action-btn edit-btn" @click.stop="editPost(post)">
                <text class="iconfont icon-edit"></text>
                <text>编辑</text>
              </view> -->
              <view class="action-btn delete-btn" @click.stop="deletePost(post)">
                <text class="iconfont icon-delete"></text>
                <text>删除</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore">
          <text v-if="isLoading">加载中...</text>
          <text v-else>上拉加载更多</text>
        </view>
        <view class="no-more" v-else>
          <text>没有更多内容了</text>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <image src="/static/images/empty-posts.png" mode="aspectFit"></image>
        <text>暂无帖子</text>
        <button class="create-btn" @click="createPost">发布新帖子</button>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentStatus: 'all',
      posts: [],
      page: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      isRefreshing: false,
      total: 0
    }
  },
  computed: {
    filteredPosts() {
      if (this.currentStatus === 'all') {
        return this.posts;
      } else if (this.currentStatus === 'published') {
        return this.posts.filter(post => post.status === 'published');
      } else if (this.currentStatus === 'deleted') {
        return this.posts.filter(post => post.status === 'deleted');
      }
      return this.posts;
    }
  },
  onLoad() {
    this.loadPosts();
  },
  onShow() {
    // 每次页面显示时刷新数据
    this.refreshPosts();
  },
  methods: {
    // 切换状态
    switchStatus(status) {
      if (this.currentStatus === status) return;
      this.currentStatus = status;
      this.refreshPosts();
    },
    
    // 加载帖子
    async loadPosts(isRefresh = false) {
      if (this.isLoading) return;
      
      this.isLoading = true;
      
      try {
        const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || uni.getStorageSync('userInfo');
        if (!userInfo) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }, 1500);
          return;
        }
        
        const res = await uniCloud.callFunction({
          name: 'getMyPosts',
          data: {
            userId: userInfo._id,
            page: isRefresh ? 1 : this.page,
            pageSize: this.pageSize,
            status: this.currentStatus === 'all' ? '' : this.currentStatus
          }
        });
        
        if (res.result.code === 0) {
          const { data: posts, total } = res.result;
          this.total = total;
          
          if (isRefresh) {
            this.posts = posts;
            this.page = 1;
          } else {
            this.posts = [...this.posts, ...posts];
            this.page++;
          }
          
          this.hasMore = this.posts.length < total;
        } else {
          uni.showToast({
            title: res.result.msg || '加载失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载帖子失败', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
        this.isRefreshing = false;
      }
    },
    
    // 刷新帖子
    refreshPosts() {
      this.page = 1;
      this.hasMore = true;
      this.posts = [];
      this.loadPosts(true);
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.isLoading) {
        this.loadPosts();
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true;
      await this.refreshPosts();
      this.isRefreshing = false;
    },
    
    // 查看帖子详情
    viewPostDetail(post) {
      uni.navigateTo({
        url: `/pages/forum/detail?id=${post._id}`
      });
    },
    
    // 编辑帖子
    editPost(post) {
      // 检查登录状态
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || uni.getStorageSync('userInfo');
      if (!userInfo) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              });
            }
          }
        });
        return;
      }
      
      // 检查权限
      if (post.userId !== userInfo._id) {
        uni.showToast({
          title: '无权编辑他人帖子',
          icon: 'none'
        });
        return;
      }
      
      // 检查帖子状态
      if (post.status === 'deleted') {
        uni.showToast({
          title: '已删除的帖子无法编辑',
          icon: 'none'
        });
        return;
      }
      
      // 跳转到编辑页面
      uni.navigateTo({
        url: `/pages/forum/post?type=edit&id=${post._id}`
      });
    },
    
    // 删除帖子
    deletePost(post) {
		console.log(post)
      // 检查登录状态
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || uni.getStorageSync('userInfo');
      if (!userInfo) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              });
            }
          }
        });
        return;
      }
      
      // 检查权限
      if (post.userId !== userInfo._id) {
        uni.showToast({
          title: '无权删除他人帖子',
          icon: 'none'
        });
        return;
      }
      
      // 检查帖子状态
      if (post.status === 'deleted') {
        uni.showToast({
          title: '帖子已删除',
          icon: 'none'
        });
        return;
      }
      
      // 显示确认对话框
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这篇帖子吗？删除后将无法恢复。',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '删除中...'
            });
            
            try {
              const result = await uniCloud.callFunction({
                name: 'deletePost',
                data: {
                  id: post._id,
                  userId: userInfo._id
                }
              });
              
              if (result.result.code === 0) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                
                // 更新本地数据
                const index = this.posts.findIndex(p => p._id === post._id);
                if (index !== -1) {
                  this.posts.splice(index, 1);
                }
                
                // 如果当前没有帖子了，刷新列表
                if (this.posts.length === 0) {
                  this.refreshPosts();
                }
              } else {
                throw new Error(result.result.msg);
              }
            } catch (e) {
              uni.showToast({
                title: e.message || '删除失败',
                icon: 'none'
              });
            } finally {
              uni.hideLoading();
            }
          }
        }
      });
    },
    
    // 创建新帖子
    createPost() {
      uni.navigateTo({
        url: '/pages/forum/post'
      });
    },
    
    // 预览图片
    previewImage(images, current) {
      uni.previewImage({
        urls: images,
        current: images[current]
      });
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const minute = date.getMinutes().toString().padStart(2, '0');
      
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'published': '已发布',
        'deleted': '已删除'
      };
      return statusMap[status] || '未知状态';
    }
  }
}
</script>

<style>
/* 引入图标字体 */
@font-face {
  font-family: "iconfont";
  src: url('//at.alicdn.com/t/c/font_4456201_0.css');
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 32rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-like:before {
  content: "\e8c0";
}

.icon-comment:before {
  content: "\e8c1";
}

.icon-edit:before {
  content: "\e8c2";
}

.icon-delete:before {
  content: "\e8c3";
}

.my-posts {
  min-height: 100vh;
  background-color: #f8f9fc;
  display: flex;
  flex-direction: column;
}

.status-bar {
  display: flex;
  background-color: #fff;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.status-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  position: relative;
  padding: 10rpx 0;
}

.status-item.active {
  color: #4a6ee0;
  font-weight: bold;
}

.status-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #4a6ee0;
  border-radius: 2rpx;
}

.post-list {
  flex: 1;
  padding: 0 20rpx;
}

.post-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.post-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  margin-right: 20rpx;
}

.post-status {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.post-status.published {
  background-color: #e6f7ff;
  color: #1890ff;
}

.post-status.deleted {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.post-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 20rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

.post-images {
  display: flex;
  margin-bottom: 20rpx;
}

.post-images image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 8rpx;
  margin-right: 10rpx;
}

.image-count {
  width: 180rpx;
  height: 180rpx;
  border-radius: 8rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36rpx;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-meta {
  display: flex;
  align-items: center;
}

.post-time {
  font-size: 24rpx;
  color: #999;
  margin-right: 20rpx;
}

.post-stats {
  font-size: 24rpx;
  color: #999;
}

.post-stats .iconfont {
  margin-right: 4rpx;
  margin-left: 10rpx;
}

.post-actions {
  display: flex;
}

.action-btn {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #666;
  margin-left: 20rpx;
}

.action-btn .iconfont {
  margin-right: 4rpx;
}

.edit-btn {
  color: #4a6ee0;
}

.delete-btn {
  color: #ff4d4f;
}

.load-more, .no-more {
  text-align: center;
  padding: 20rpx 0;
  font-size: 24rpx;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-state image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-state text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.create-btn {
  background: linear-gradient(135deg, #4a6ee0, #3a5bc7);
  color: #fff;
  font-size: 28rpx;
  padding: 0 40rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
}
</style> 